// pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 电机信息
    motorInfo: {
      id: '',
      name: 'LMS系列直线电机',
      model: 'LMS-165-050',
      brand: 'HIWIN上银',
      status: 'available',
      image: '/static/images/motor-lms.png',
      description: '高精度直线电机，采用无铁芯设计，具有零磁滞、低发热、高精度等特点。适用于半导体、电子装配、医疗设备等高精度应用场景。',
      performanceParams: [
        { key: 'maxForce', label: '最大推力', value: '165', unit: 'N' },
        { key: 'continuousForce', label: '连续推力', value: '50', unit: 'N' },
        { key: 'maxSpeed', label: '最大速度', value: '5.0', unit: 'm/s' },
        { key: 'maxAccel', label: '最大加速度', value: '50', unit: 'm/s²' },
        { key: 'resolution', label: '分辨率', value: '0.1', unit: 'μm' },
        { key: 'repeatability', label: '重复精度', value: '±1', unit: 'μm' }
      ],
      physicalParams: [
        { key: 'length', label: '长度', value: '280', unit: 'mm' },
        { key: 'width', label: '宽度', value: '70', unit: 'mm' },
        { key: 'height', label: '高度', value: '45', unit: 'mm' },
        { key: 'weight', label: '重量', value: '2.1', unit: 'kg' },
        { key: 'stroke', label: '行程', value: '50-1000', unit: 'mm' },
        { key: 'material', label: '材质', value: '铝合金', unit: '' }
      ],
      electricalParams: [
        { key: 'voltage', label: '额定电压', value: '320', unit: 'V' },
        { key: 'current', label: '额定电流', value: '5.2', unit: 'A' },
        { key: 'power', label: '额定功率', value: '400', unit: 'W' },
        { key: 'resistance', label: '电阻', value: '3.8', unit: 'Ω' },
        { key: 'inductance', label: '电感', value: '12.5', unit: 'mH' },
        { key: 'forceConstant', label: '力常数', value: '95', unit: 'N/A' }
      ],
      applications: [
        {
          id: 1,
          title: '半导体晶圆检测设备',
          description: '用于晶圆载台的高精度定位，要求极高的重复精度和稳定性',
          image: '/static/images/app-semiconductor.png',
          tags: ['高精度', '半导体', '无尘环境']
        },
        {
          id: 2,
          title: '医疗设备分析仪',
          description: '应用于血液分析仪的样品传输系统，确保检测精度',
          image: '/static/images/app-medical.png',
          tags: ['医疗', '精密', '可靠性']
        }
      ],
      documents: [
        {
          id: 1,
          title: '产品规格书',
          description: '详细技术参数和安装尺寸',
          type: 'pdf',
          url: '/docs/LMS-165-050-spec.pdf'
        },
        {
          id: 2,
          title: '安装手册',
          description: '安装指导和调试说明',
          type: 'pdf',
          url: '/docs/LMS-165-050-install.pdf'
        },
        {
          id: 3,
          title: '3D模型文件',
          description: 'STEP格式3D模型文件',
          type: 'step',
          url: '/models/LMS-165-050.step'
        }
      ]
    },
    
    // UI状态
    activeTab: 'performance',
    activeCurve: 'force',
    isFullscreen: false,
    isCollected: false,
    
    // 3D相关
    isLoading3D: true,
    load3DError: false,
    canvas: null,
    scene: null,
    camera: null,
    renderer: null,
    model: null,
    
    // 触摸交互
    lastTouchX: 0,
    lastTouchY: 0,
    isRotating: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取传递的电机ID
    if (options.id) {
      this.setData({
        'motorInfo.id': options.id
      });
      this.loadMotorDetail(options.id);
    }
    
    // 初始化3D场景
    this.init3DScene();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // 渲染性能曲线
    this.renderCurve('force');
  },

  /**
   * 加载电机详细信息
   */
  loadMotorDetail(motorId) {
    // 模拟API调用
    wx.showLoading({ title: '加载中...' });
    
    setTimeout(() => {
      // 这里应该调用真实的API
      // const motorData = await api.getMotorDetail(motorId);
      // this.setData({ motorInfo: motorData });
      
      wx.hideLoading();
    }, 1000);
  },

  /**
   * 初始化3D场景
   */
  init3DScene() {
    wx.createSelectorQuery()
      .select('#motor3d')
      .node(res => {
        const canvas = res.node;
        const ctx = canvas.getContext('webgl');
        
        // 设置canvas尺寸
        const info = wx.getSystemInfoSync();
        const dpr = info.pixelRatio;
        canvas.width = info.windowWidth * dpr;
        canvas.height = 500 * dpr / 750 * info.windowWidth;
        
        this.setData({ canvas });
        
        // 初始化Three.js场景（需要引入three.js库）
        this.setupThreeJS(canvas, ctx);
      })
      .exec();
  },

  /**
   * 设置Three.js场景
   */
  setupThreeJS(canvas, ctx) {
    // 这里需要引入适用于微信小程序的Three.js版本
    // 由于当前环境限制，提供基本的实现思路
    
    try {
      // 创建场景、相机、渲染器
      // const scene = new THREE.Scene();
      // const camera = new THREE.PerspectiveCamera(75, canvas.width / canvas.height, 0.1, 1000);
      // const renderer = new THREE.WebGLRenderer({ canvas, context: ctx });
      
      // 添加灯光
      // const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
      // const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
      
      // 加载3D模型
      this.load3DModel();
      
      // 开始渲染循环
      this.animate();
      
    } catch (error) {
      console.error('3D初始化失败:', error);
      this.setData({
        isLoading3D: false,
        load3DError: true
      });
    }
  },

  /**
   * 加载3D模型
   */
  load3DModel() {
    // 模拟加载过程
    // setTimeout(() => {
    //   this.setData({
    //     isLoading3D: false,
    //     load3DError: false
    //   });
    // }, 2000);
    
    // 实际实现中，这里应该加载GLTF或STEP文件
    const loader = new THREE.GLTFLoader();
    loader.load('/images/3d/result.gltf', (gltf) => {
      this.setData({ model: gltf.scene });
      scene.add(gltf.scene);
    });
  },

  /**
   * 动画循环
   */
  animate() {
    // requestAnimationFrame(this.animate.bind(this));
    // if (this.data.renderer) {
    //   this.data.renderer.render(this.data.scene, this.data.camera);
    // }
  },

  /**
   * 触摸开始
   */
  onTouchStart(e) {
    const touch = e.touches[0];
    this.setData({
      lastTouchX: touch.x,
      lastTouchY: touch.y,
      isRotating: true
    });
  },

  /**
   * 触摸移动
   */
  onTouchMove(e) {
    if (!this.data.isRotating) return;
    
    const touch = e.touches[0];
    const deltaX = touch.x - this.data.lastTouchX;
    const deltaY = touch.y - this.data.lastTouchY;
    
    // 更新模型旋转
    if (this.data.model) {
      // this.data.model.rotation.y += deltaX * 0.01;
      // this.data.model.rotation.x += deltaY * 0.01;
    }
    
    this.setData({
      lastTouchX: touch.x,
      lastTouchY: touch.y
    });
  },

  /**
   * 触摸结束
   */
  onTouchEnd() {
    this.setData({ isRotating: false });
  },

  /**
   * 切换全屏
   */
  toggleFullscreen() {
    this.setData({
      isFullscreen: !this.data.isFullscreen
    });
  },

  /**
   * 重置视图
   */
  resetView() {
    if (this.data.model) {
      // 重置模型位置和旋转
      // this.data.model.rotation.set(0, 0, 0);
      // this.data.camera.position.set(0, 0, 5);
    }
  },

  /**
   * 重新加载3D模型
   */
  reload3D() {
    this.setData({
      isLoading3D: true,
      load3DError: false
    });
    this.load3DModel();
  },

  /**
   * 切换参数标签
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  /**
   * 切换曲线标签
   */
  switchCurve(e) {
    const curve = e.currentTarget.dataset.curve;
    this.setData({ activeCurve: curve });
    this.renderCurve(curve);
  },

  /**
   * 渲染性能曲线
   */
  renderCurve(type) {
    const canvasId = `curve${type}`;
    
    wx.createSelectorQuery()
      .select(`#${canvasId}`)
      .node(res => {
        const canvas = res.node;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸
        const info = wx.getSystemInfoSync();
        const dpr = info.pixelRatio;
        canvas.width = (info.windowWidth - 64) * dpr;
        canvas.height = 400 * dpr / 750 * info.windowWidth;
        
        ctx.scale(dpr, dpr);
        
        // 绘制曲线
        this.drawCurve(ctx, type, canvas.width / dpr, canvas.height / dpr);
      })
      .exec();
  },

  /**
   * 绘制曲线图
   */
  drawCurve(ctx, type, width, height) {
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 设置样式
    ctx.strokeStyle = '#ce1b28';
    ctx.lineWidth = 3;
    ctx.font = '12px Arial';
    ctx.fillStyle = '#6c757d';
    
    // 绘制坐标轴
    const margin = 40;
    const chartWidth = width - 2 * margin;
    const chartHeight = height - 2 * margin;
    
    // X轴
    ctx.beginPath();
    ctx.moveTo(margin, height - margin);
    ctx.lineTo(width - margin, height - margin);
    ctx.stroke();
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(margin, margin);
    ctx.lineTo(margin, height - margin);
    ctx.stroke();
    
    // 根据类型绘制不同的曲线
    const data = this.getCurveData(type);
    
    if (data.length > 0) {
      ctx.beginPath();
      
      data.forEach((point, index) => {
        const x = margin + (point.x / 100) * chartWidth;
        const y = height - margin - (point.y / 100) * chartHeight;
        
        if (index === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      });
      
      ctx.stroke();
    }
    
    // 添加标签
    ctx.fillText(this.getCurveLabel(type).x, width - 60, height - 10);
    ctx.save();
    ctx.translate(15, height / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.fillText(this.getCurveLabel(type).y, 0, 0);
    ctx.restore();
  },

  /**
   * 获取曲线数据
   */
  getCurveData(type) {
    // 模拟数据
    const data = {
      force: [
        { x: 0, y: 0 }, { x: 20, y: 80 }, { x: 40, y: 95 },
        { x: 60, y: 100 }, { x: 80, y: 90 }, { x: 100, y: 70 }
      ],
      speed: [
        { x: 0, y: 0 }, { x: 25, y: 60 }, { x: 50, y: 85 },
        { x: 75, y: 95 }, { x: 100, y: 100 }
      ],
      thermal: [
        { x: 0, y: 20 }, { x: 30, y: 45 }, { x: 60, y: 70 },
        { x: 90, y: 85 }, { x: 100, y: 90 }
      ]
    };
    
    return data[type] || [];
  },

  /**
   * 获取曲线标签
   */
  getCurveLabel(type) {
    const labels = {
      force: { x: '电流(A)', y: '推力(N)' },
      speed: { x: '推力(N)', y: '速度(m/s)' },
      thermal: { x: '时间(min)', y: '温度(°C)' }
    };
    
    return labels[type] || { x: '', y: '' };
  },

  /**
   * 下载文档
   */
  downloadDoc(e) {
    const doc = e.currentTarget.dataset.doc;
    
    wx.showLoading({ title: '准备下载...' });
    
    // 模拟下载
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '下载完成',
        icon: 'success'
      });
    }, 1500);
  },

  /**
   * 分享电机
   */
  shareMotor() {
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  /**
   * 收藏电机
   */
  collectMotor() {
    const isCollected = !this.data.isCollected;
    this.setData({ isCollected });
    
    wx.showToast({
      title: isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  /**
   * 联系技术支持
   */
  contactSupport() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567'
    });
  },

  /**
   * 添加到项目
   */
  addToProject() {
    wx.showModal({
      title: '添加到项目',
      content: '确定要将此电机添加到当前项目中吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
        }
      }
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  /**
   * 分享功能
   */
  onShareAppMessage() {
    return {
      title: `${this.data.motorInfo.name} - 电机详情`,
      path: `/pages/detail/detail?id=${this.data.motorInfo.id}`,
      imageUrl: this.data.motorInfo.image
    };
  }
})